{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "source": [
    "import sys\n",
    "from pathlib import Path\n",
    "curr_path = str(Path().absolute()) # 当前文件所在绝对路径\n",
    "parent_path = str(Path().absolute().parent) # 父路径\n",
    "sys.path.append(parent_path) # 添加路径到系统路径\n",
    "\n",
    "import numpy as np"
   ],
   "outputs": [],
   "metadata": {}
  },
  {
   "cell_type": "markdown",
   "source": [
    "## 计算高斯核\n",
    "\n",
    "高斯核数学表达为：$K(x, x')=\\exp\\left(-\\gamma\\|x-x'\\|^{2}\\right)$   \n",
    "用矩阵表达则为：$K(i, j)=\\exp\\left(-\\gamma\\|x_i-x_j\\|^{2}\\right)$   \n",
    "其中数据集矩阵$x$的维度为$(m,)$，则高斯核$K$的维度为$(m,m)$\n"
   ],
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "source": [
    "def calc_kernel(X_train):\n",
    "        '''\n",
    "        计算核函数\n",
    "        使用的是高斯核 详见“7.3.3 常用核函数” 式7.90\n",
    "        :return: 高斯核矩阵\n",
    "        '''\n",
    "        #初始化高斯核结果矩阵 大小 = 训练集长度m * 训练集长度m\n",
    "        # k[i][j] = Xi * Xj\n",
    "        m =  X_train.shape[0]\n",
    "        k = [[0 for i in range(m)] for j in range(m)]\n",
    "        #大循环遍历Xi，Xi为式7.90中的x\n",
    "        for i in range(m):\n",
    "            #得到式7.90中的X\n",
    "            X = X_train[i, :]\n",
    "            #小循环遍历Xj，Xj为式7.90中的Z\n",
    "            # 由于 Xi * Xj 等于 Xj * Xi，一次计算得到的结果可以\n",
    "            # 同时放在k[i][j]和k[j][i]中，这样一个矩阵只需要计算一半即可\n",
    "            #所以小循环直接从i开始\n",
    "            for j in range(i, m):\n",
    "                #获得Z\n",
    "                Z = X_train[j, :]\n",
    "                #先计算||X - Z||^2\n",
    "                result = (X - Z) * (X - Z).T\n",
    "                #分子除以分母后去指数，得到的即为高斯核结果\n",
    "                result = np.exp(-1 * result / (2 * self.sigma**2))\n",
    "                #将Xi*Xj的结果存放入k[i][j]和k[j][i]中\n",
    "                k[i][j] = result\n",
    "                k[j][i] = result\n",
    "        #返回高斯核矩阵\n",
    "        return k"
   ],
   "outputs": [],
   "metadata": {}
  }
 ],
 "metadata": {
  "orig_nbformat": 4,
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}